'use strict';

const db = uniCloud.database()
const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  // 1. 获取 token
  const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
  if (!token) {
    return { code: 401, msg: '未登录' }
  }
  // 2. 解析 token
  const uniId = uniIdCommon.createInstance({ context })
  const tokenRes = await uniId.checkToken(token)
  if (tokenRes.code !== 0) {
    return { code: 401, msg: 'token无效或已过期' }
  }
  const uid = tokenRes.uid

  // 3. 构建筛选条件
  const { month, type } = event
  
  // 4. 查询支付记录
  let paymentRes = { data: [] }
  if (!type || type !== 'task_income') {
    let paymentWhere = { user_id: uid }
    if (type && type !== 'task_income') {
      paymentWhere.type = type
    }
    
    paymentRes = await db.collection('payment_records')
      .where(paymentWhere)
      .orderBy('create_time', 'desc')
      .get()
  }

  // 5. 查询收入记录（如果type为task_income或未指定type）
  let incomeRes = { data: [] }
  if (!type || type === 'task_income') {
    incomeRes = await db.collection('task_income_records')
      .where({ receiver_id: uid, status: 'completed' })
      .orderBy('complete_time', 'desc')
      .get()
  }

  // 6. 合并数据
  const allRecords = [
    ...paymentRes.data.map(record => ({ 
      ...record, 
      recordType: 'payment',
      displayTime: record.create_time
    })),
    ...incomeRes.data.map(record => ({ 
      ...record, 
      recordType: 'income',
      type: 'task_income',
      amount: record.reward_amount,
      payment_method: 'system',
      status: 'success',
      displayTime: record.complete_time || record.create_time,
      desc: '任务完成收入'
    }))
  ]

  // 7. 去重处理 - 基于 _id 去重
  const uniqueRecords = []
  const seenIds = new Set()
  
  for (const record of allRecords) {
    if (!seenIds.has(record._id)) {
      seenIds.add(record._id)
      uniqueRecords.push(record)
    }
  }

  console.log('[getPaymentRecords] 合并前记录数:', allRecords.length, '去重后记录数:', uniqueRecords.length)
  let data = uniqueRecords
  
  // 按时间排序
  data.sort((a, b) => (b.displayTime || 0) - (a.displayTime || 0))
  
  // 按月筛选
  if (month) {
    data = data.filter(item => {
      if (!item.displayTime) return false
      let str = ''
      if (typeof item.displayTime === 'string') {
        str = item.displayTime
      } else if (typeof item.displayTime === 'number') {
        str = new Date(item.displayTime).toISOString()
      } else if (item.displayTime instanceof Date) {
        str = item.displayTime.toISOString()
      }
      return str.startsWith(month)
    })
  }

  return {
    code: 200,
    data
  }
} 